import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import Skeleton from '@/components/Skeleton';
import { useAppDispatch, useAppSelector } from '@/store';
import { clearDetailAction, followAction, getArticleDetailAction } from '@/store/action/article';
import { clearCommentAction, getCommentsByIdAction } from '@/store/action/comment';
import { InfiniteScroll, Popup } from 'antd-mobile';
import classNames from 'classnames';
import dayjs from 'dayjs';
import DOMPurify from 'dompurify';
import hljs from 'highlight.js';
import 'highlight.js/styles/vs2015.css';
import { map } from 'lodash';
import { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router-dom';
import CommentFooter from './components/CommentFooter';
import CommentItem from './components/CommentItem';
import CommentReply from './components/CommentReply';
import NoComment from './components/NoComment';
import styles from './index.module.scss';

export default function Article() {
  const { id } = useParams<{ id: string }>();
  const { detail } = useAppSelector((state) => state.article);
  const { commentData, originComment } = useAppSelector((state) => state.comment);
  const { results, last_id, end_id } = commentData;

  const [visible, setVisible] = useState(false);

  const dispatch = useAppDispatch();

  const warpRef = useRef<HTMLDivElement>(null);
  const authRef = useRef<HTMLDivElement>(null);
  const commentRef = useRef<HTMLDivElement>(null);
  const clickedRef = useRef(false);

  const showComment = () => {
    if (clickedRef.current) {
      warpRef.current?.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      warpRef.current?.scrollTo({ top: commentRef.current!.offsetTop - 46, behavior: 'smooth' });
    }
    clickedRef.current = !clickedRef.current;
  };

  const loadMore = async () => {
    await dispatch(getCommentsByIdAction(id, 'a', last_id));
  };

  useEffect(() => {
    dispatch(getArticleDetailAction(id));
    dispatch(getCommentsByIdAction(id, 'a'));

    return () => {
      dispatch(clearDetailAction());
      dispatch(clearCommentAction());
    };
  }, [dispatch, id]);

  useEffect(() => {
    if (!detail.art_id) return;

    hljs.configure({
      ignoreUnescapedHTML: true,
    });

    const codes = document.querySelectorAll('.dg-html pre code');
    if (codes.length) {
      codes.forEach((el) => hljs.highlightElement(el as any));
    }

    const pre = document.querySelectorAll('.dg-html pre');
    if (pre.length > 0) {
      return pre.forEach((el) => hljs.highlightElement(el as any));
    }
  }, [detail.art_id]);

  const scrollFn = () => {
    const { top } = authRef.current!.getBoundingClientRect();

    if (top > 10) {
      setVisible(false);
    } else {
      setVisible(true);
    }
  };

  useEffect(() => {
    if (!detail.art_id) return;

    warpRef.current?.addEventListener('scroll', scrollFn);
    const warpDom = warpRef.current;
    return () => {
      warpDom?.removeEventListener('scroll', scrollFn);
    };
  }, [detail.art_id]);

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar right={<Icon type="icongengduo" />}>
          {visible && (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span
                onClick={() => dispatch(followAction())}
                className={classNames('follow', detail.is_followed ? 'followed' : '')}
              >
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {detail.art_id ? (
          <div className="wrapper" ref={warpRef}>
            <div className="article-wrapper">
              <div className="header">
                <h1 className="title">{detail.title}</h1>

                <div className="info">
                  <span>{dayjs(detail.pubdate).format('YYYY-MM-DD')}</span>
                  <span>{detail.read_count} 阅读</span>
                  <span>{detail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authRef}>
                  <img src={detail.aut_photo} alt="" />
                  <span className="name">{detail.aut_name}</span>
                  <span
                    onClick={() => dispatch(followAction())}
                    className={classNames({ follow: detail.is_followed })}
                  >
                    {detail.is_followed ? '已关注' : '关注'}{' '}
                  </span>
                </div>
              </div>

              <div className="content">
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{
                    __html: DOMPurify.sanitize(detail.content),
                  }}
                />
                <div className="date">
                  发布文章时间：
                  {dayjs().from(detail.pubdate)}
                </div>
                <div className="divider"></div>
                <div className="comment" ref={commentRef}>
                  <div className="comment-header">
                    <span>全部评论（{detail.comm_count}）</span>
                    <span>{detail.like_count} 点赞</span>
                  </div>
                  {detail.comm_count === 0 ? (
                    <NoComment />
                  ) : (
                    <div className="comment-list">
                      {map(results, (item) => {
                        return <CommentItem key={item.com_id} comment={item} />;
                      })}
                      {!!results?.length && (
                        <InfiniteScroll loadMore={loadMore} hasMore={last_id !== end_id} />
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        ) : (
          <Skeleton />
        )}
      </div>

      <CommentFooter onClick={showComment} detail={detail} />

      <Popup
        // 2. 关闭时销毁组件
        destroyOnClose
        visible={!!originComment.com_id}
        position="right"
      >
        <CommentReply />
      </Popup>
    </div>
  );
}
